/**
 * 实现instanceof操作符
 * @param instance 实例对象
 * @param constructor 构造函数
 * @returns {boolean}
 */
function _instanceof(instance, constructor) {
  // TODO: 完善instanceof逻辑
  // 递归实现：
  // 原型链已经到达顶端还没有找到 或者 参数是原始值 返回false
  /* if(instance.__proto__ !== null && (typeof instance === 'function' || typeof instance === 'object')){
    let p = instance.__proto__
    if(p === constructor.prototype){
        return true
    } else {
        // arguments.callee返回arguments中this的指向，一般用于匿名函数
        return _instanceof(p,constructor)
    } 
  } else {
    return false
  } */
  // 非递归实现
  let p = instance.__proto__;
  while(p && (typeof instance === 'function' || typeof instance === 'object')){
    if(p === constructor.prototype) {
      return true;
    }
    p = p.__proto__;
  }
  return false;
}

// 测试用例
let Foo = function () {
};
let foo = new Foo();
assert([], Array);
assert({ foo: 'bar' }, Object);
assert(Foo, Function);
assert(foo, Function);
assert(foo, Object);
assert(Foo, Object);
assert(foo, Foo);
assert(Function, Function);//自己造自己
assert(Object.prototype, Object);
assert(1, Object);//参数是原始值

function assert(left, right) {
  const result1 = _instanceof(left, right);
  const result2 = left instanceof right;
  const result = result1 === result2 ? 'success' : 'fail';
  console.log(result);
  return result;
}
